/*
  学习目标：实现清除评论的功能、 条件渲染显示暂无评论
*/
import React from 'react';
import './index.css';

export default class App extends React.Component {
  state = {
    username: '',
    content: '',
    list: [
      {
        id: 1,
        username: '思聪',
        content: '想你的夜',
      },
      {
        id: 2,
        username: '马芸',
        content: '我对钱不感兴趣',
      },
      {
        id: 3,
        username: '王简林',
        content: '实现一个小目标',
      },
    ],
  };

  handleChange = (e) => {
    this.setState({ [e.target.name]: e.target.value });
  };

  handleDelById = (id) => {
    const { list } = this.state;
    const newList = list.filter((item) => item.id !== id);
    this.setState({ list: newList });
  };

  // 1. 定义一个清除评论的方法
  handleClear = () => {
    this.setState({ list: [] });
  };

  handleAdd = (e) => {
    e.preventDefault();
    const { username, content, list } = this.state;

    if (!username.trim() || !content.trim()) {
      this.setState({ username: '', content: '' });
      alert('请输入内容');
      return;
    }
    const newItem = {
      username,
      content,
      id: Date.now(),
    };
    this.setState({ list: [newItem, ...list], username: '', content: '' });
  };

  render() {
    const { list, username, content } = this.state;
    return (
      <div className="app">
        <form>
          <input
            value={username}
            onChange={this.handleChange}
            name="username"
            className="user"
            type="text"
            placeholder="请输入评论人"
          />
          <br />
          <textarea
            value={content}
            onChange={this.handleChange}
            name="content"
            className="content"
            cols="30"
            rows="10"
            placeholder="请输入评论内容"
          />
          <br />
          <button onClick={this.handleAdd}>发表评论</button>
          {/* 2. 点击按钮触发 */}
          <button onClick={this.handleClear} type="button">
            清空评论
          </button>
        </form>
        {/* 3. 条件渲染 */}
        {list.length ? (
          <ul>
            {list.map((item) => {
              return (
                <li key={item.id}>
                  <h3>评论人: {item.username}</h3>
                  <p>评论内容：{item.content}</p>
                  <button onClick={() => this.handleDelById(item.id)}>删除</button>
                </li>
              );
            })}
          </ul>
        ) : (
          <div>暂无数据</div>
        )}
      </div>
    );
  }
}
